/**
 * Project: ld.biz.service
 * 
 * File Created at 2012-9-23
 * $Id$
 * 
 * Copyright 1999-2100 Alibaba.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.liangdev.biz.core.autocode;

import java.io.File;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.liangdev.biz.entity.autocode.AutoCodeFile;
import com.liangdev.biz.entity.autocode.TableMetaData;

/**
 * TODO Comment of AutoCodeFactory
 * 
 * @author chongan.wangca
 */
public class AutoCodeFactory {

    private Logger              logger = LoggerFactory.getLogger(AutoCodeFactory.class);

    private TemplateFileManager templateFileManager;
    private TemplateRenderer    templateRenderer;
    private DBMetaDataManager   dbMetaDataManager;

    public AutoCodeFile generate(Long dbInfoId, Long templateInfoId, String tableName)
            throws Exception {
        TableMetaData tableMetaData = dbMetaDataManager.getTable(dbInfoId, tableName);
        Map<String, Object> templateContextMap = VelocityContextConstructor.make(tableMetaData);
        File templateFile = templateFileManager.getTemplateFile(templateInfoId);
        String content = templateRenderer.render(templateFile, templateContextMap);
        if (logger.isInfoEnabled()) {
            logger.info(content);
        }
        AutoCodeFile autoCodeFile = getAutoCodeFile(dbInfoId, templateInfoId, tableName, content);
        return autoCodeFile;
    }

    /**
     * @param dbInfoId
     * @param templateInfoId
     * @param tableName
     * @param content
     * @return
     */
    private AutoCodeFile getAutoCodeFile(Long dbInfoId, Long templateInfoId, String tableName,
                                         String content) {
        AutoCodeFile autoCodeFile = new AutoCodeFile();
        autoCodeFile.setContent(content);
        autoCodeFile.setDbInfoId(dbInfoId);
        autoCodeFile.setTemplateInfoId(templateInfoId);
        autoCodeFile.setTableName(tableName);
        //TODO-目前暂时用表名替代
        autoCodeFile.setFileName(tableName);
        return autoCodeFile;
    }

    public void setTemplateFileManager(TemplateFileManager templateFileManager) {
        this.templateFileManager = templateFileManager;
    }

    public void setTemplateRenderer(TemplateRenderer templateRenderer) {
        this.templateRenderer = templateRenderer;
    }

    public void setDbMetaDataManager(DBMetaDataManager dbMetaDataManager) {
        this.dbMetaDataManager = dbMetaDataManager;
    }

}
